﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecognitionForm.Core
{
    public static class ImageBase64ConvertExt
    {
        //图片 转为    base64编码的文本
        public static string ImageToBase64String(this string Imagefilename)
        {
            using (Bitmap bmp = new Bitmap(Imagefilename))
            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
        }


        //base64编码的文本 转为    图片
        public static void Base64StringToImage(this string txtFileName, string savePath)
        {
            using (FileStream ifs = new FileStream(txtFileName, FileMode.Open, FileAccess.Read))
            using (StreamReader sr = new StreamReader(ifs))
            {
                String inputStr = sr.ReadToEnd();
                byte[] arr = Convert.FromBase64String(inputStr);
                using (MemoryStream ms = new MemoryStream(arr))
                using (Bitmap bmp = new Bitmap(ms))
                {
                    //bmp.Save(txtFileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
                    //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
                    //bmp.Save(txtFileName + ".png", ImageFormat.Png);
                    bmp.Save(Path.Combine(savePath, txtFileName + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }

            if (File.Exists(txtFileName))
            {
                File.Delete(txtFileName);
            }

        }
    }
}
